package com.boarsoft.sofa.router;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.ArrayUtils;

import com.alipay.sofa.rpc.bootstrap.ConsumerBootstrap;
import com.alipay.sofa.rpc.client.ProviderInfo;
import com.alipay.sofa.rpc.client.Router;
import com.alipay.sofa.rpc.core.request.SofaRequest;
import com.alipay.sofa.rpc.ext.Extension;
import com.alipay.sofa.rpc.filter.AutoActive;
import com.boarsoft.common.Util;

@Extension(value = "tagBaseRouter")
@AutoActive(consumerSide = true)
public class TagBaseRouterImpl extends Router {
	@SuppressWarnings("rawtypes")
	@Override
	public void init(ConsumerBootstrap consumerBootstrap) {

	}

	@SuppressWarnings("rawtypes")
	@Override
	public boolean needToLoad(ConsumerBootstrap consumerBootstrap) {
		return true;
	}

	@Override
	public List<ProviderInfo> route(SofaRequest request, List<ProviderInfo> providerInfos) {
		String ts = System.getProperty("rpc.tag", "Z");
		String[] ta = ts.split(",");
		List<ProviderInfo> lt = new ArrayList<>();
		List<ProviderInfo> at = new ArrayList<>();
		for (ProviderInfo p : providerInfos) {
			String t = p.getAttr("tag");
			// 允许调外部系统（无tag）
			if (Util.strIsEmpty(t)) {
				lt.add(p);
				continue;
			}
			// 1、ts = X,Z 且 t = X,Z（ta [X,Y]，不包含"X,Z"）
			// 2、ts = Z 且 t = Z
			if (ts.equals(t)) {
				at.add(p);
				continue;
			}
			if (ArrayUtils.contains(ta, t)) {
				lt.add(p);
			}
		}
		return at.isEmpty() ? lt : at;
	}
}
